<?php
/**
 * Created by PhpStorm.
 * User: xiaoxin
 * Date: 2018/10/17 0017
 * Time: 14:02
 */
class Captcha
{
	public $src;//画布
	public $code;
	public $config = [
		'width' => 300, //画布宽度
		'height'=> 100,	//画布高度
		'num' => '4',	//验证码个数
		'is_dot' => '5000',	//干扰文字个数
		'is_dot_fontSize' => '14',	//干扰文字大小
		'fontSize' =>30,	//验证码文字大小
	];//配置

	/**
	 * 初始化配置
	 * Captcha constructor.
	 * @param array $config 传过来的数组
	 */
	function __construct($config=array()){
		$this->config = array_merge($this->config,$config);
	}

	/**
	 * 被客户端调用的方法
	 */
	public function code(){
		$this->_create();
		$this->_disturb();
		$this->_text();
		$this->_output();
	}

	/**
	 * 创建画布
	 */
	protected function _create(){
		$this->src = imageCreateTrueColor($this->config['width'],$this->config['height']);
		$color = imageColorAllocate($this->src,255,255,255);
		imageFill($this->src,0,0,$color);
	}

	/**
	 * 创建干扰文字
	 */
	protected function _disturb(){
		$str = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM123456789';
		for ($i=0;$i<$this->config['is_dot']; $i++){
			$color = imageColorAllocate($this->src ,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
			$text = $str[mt_rand(0,strlen($str)-1)];
			imagettftext ( $this->src  , $this->config['is_dot_fontSize'], mt_rand(-30,30) ,mt_rand(0,$this->config['width'])  , mt_rand(0,$this->config['width']) , $color ,'Alpha Thin.ttf',$text);
		}
	}

	/**
	 *创建验证码文字
	 */
	protected function _text(){
		session_start();
		$arr ='' ;
		$str = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM123456789';
		$num = $this->config['num'];
		for ($i=0; $i <$num ; $i++) {
			$color = imageColorAllocate($this->src ,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
			$this->code = $str[mt_rand(0,strlen($str)-1)];
			$arr.=$this->code;
			$fontsize = $this->config['fontSize'];
			$y = ($this->config['height']+$fontsize)/2;
			$diff = ($this->config['width']/$num)-$fontsize > 0 ? ($this->config['width']/$num)-$fontsize : 0;
			$x = ($this->config['width']/$num)*$i+($diff)/2;
			imagettftext ($this->src , $fontsize , mt_rand(-30,30), $x , $y ,$color , 'Alpha Thin.ttf' , $this->code);
		}
		$arr = strtolower($arr);
		$_SESSION['code'] = $arr;
	}

	/**
	 * 输出图片
	 */
	protected function _output(){
		header("Content-type: image/png");
		imagepng($this->src);
	}
}